package com.vtech.ont.file.impl;

import com.vtech.ont.file.OntFileService;
import com.vtech.ont.file.config.OntFileConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.util.FileManager;
import org.apache.jena.util.LocationMapper;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * TODO
 *
 * @author houzhiwei
 * @date 2017/7/19 16:19
 */
@Slf4j
@Service
public class OntFileServiceImpl implements OntFileService {

    @Override
    public OntModel openRdfFile(String filename) {
        OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
        RDFDataMgr.read(model, filename);
        return model;
    }

    @Override
    public OntModel loadOntModelWithLocMapper(String locMapperPath, String baseOntPath) {
        OntModel model = ModelFactory.createOntologyModel();
        LocationMapper locMapper = readLocationMapping(locMapperPath);
        model.getDocumentManager().setProcessImports(true);
        FileManager fileManager = model.getDocumentManager().getFileManager();
        fileManager.setLocationMapper(locMapper);
        fileManager.setModelCaching(true);
        fileManager.readModel(model, baseOntPath, "RDF/XML");
        model.loadImports();
        log.info("ont model and its imports loaded");
        return model;
    }

    @Override
    public OntModel loadOntModelWithLocMapper(String baseOntPath) {
        return loadOntModelWithLocMapper(null, baseOntPath);
    }

    @Override
    public LocationMapper readLocationMapping(String path) {
        if (StringUtils.isBlank(path))
            path = OntFileConfiguration.DEFAULT_LOCATION_MAPPER;
        StringBuilder locSB = new StringBuilder();
        path = OntFileServiceImpl.class.getResource(path).getFile();// 还需要在web环境下测试
        locSB.append(new File(path).getName());// 桌面环境下不需要上一行也能找到文件
        locSB.append(";");
        locSB.append(path);
        LocationMapper locMapper = new LocationMapper(locSB.toString());
        if (!locMapper.listAltEntries().hasNext())// path路径为web运行时的路径，不能用于本地运行测试
            locMapper = readLocalLocationMapper();
        return locMapper;
    }

    //---------------------------------- internal functions ------------------------------//

    // 本地测试环境下
    private static LocationMapper readLocalLocationMapper()
    {
        StringBuilder locSB = new StringBuilder();
        String path = OntFileConfiguration.LOCAL_LOCATION_MAPPER;
        locSB.append(new File(path).getName());// 桌面环境下不需要上一行也能找到文件
        locSB.append(";");
        locSB.append(path);
        log.info("read local location-mapper");
        LocationMapper locMapper = new LocationMapper(locSB.toString());
        return locMapper;
    }
}
